package com.dwxt.cdms.service;

import com.dwxt.cdms.admin.service.UserServiceAdmin;
import com.dwxt.cdms.dao.CustomerMapper;
import com.dwxt.cdms.dao.RelationMapper;
import com.dwxt.cdms.entity.Customer;
import com.dwxt.cdms.entity.Relation;
import com.dwxt.cdms.entity.RelationExample;
import com.dwxt.cdms.util.BirthDayUtil;
import com.dwxt.common.base.BaseResult;
import com.dwxt.common.base.StatusCode;
import com.dwxt.common.base.YesOrNo;
import com.dwxt.common.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class RelationService {

    @Autowired
    private RelationMapper relationMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private UserServiceAdmin userServiceAdmin;

    public BaseResult insert(Relation[] relations) {
        for (Relation relation : relations) {
            if (relation.getCustomerId().equals(relation.getRelateId())) {
                return BaseResult.build(StatusCode.CAN_NOT_BINDYOURSELF);
            }
            relationMapper.insertSelective(relation);
        }
        return BaseResult.ok();
    }

    public BaseResult selectRelationCustomer(Integer customerId, String type,String phone) {
        List<Map> list = new ArrayList<>();
        if ("my".equals(type)) {
            Customer customer1 = customerMapper.selectByPrimaryKey(customerId);
            if (customer1 == null) {
                log.error("id:" + customerId);
                return BaseResult.build(StatusCode.PERMISSION_FAIL);
            }
            if (StringUtils.isNotBlank(customer1.getIdNumber())) {
                customer1.setAge(BirthDayUtil.getAgeByIDNumber(customer1.getIdNumber()));
            }
            Map map1 = JsonUtils.jsonToPojo(JsonUtils.objectToJson(customer1), Map.class);
            map1.put("isDefault", 0);
            map1.put("dutyList", customerMapper.selectCustomerIndexRelationPeople(customer1.getId()));
            list.add(map1);
        }
        List<Relation> relations = relationMapper.selectByCustomerIdAndPhone(customerId,phone);
        for (Relation relation : relations) {
            Customer customer = customerMapper.selectByPrimaryKey(relation.getRelateId());
            if (customer != null) {
                if (StringUtils.isNotBlank(customer.getIdNumber())) {
                    customer.setAge(BirthDayUtil.getAgeByIDNumber(customer.getIdNumber()));
                }
                Map map = JsonUtils.jsonToPojo(JsonUtils.objectToJson(customer), Map.class);
                map.put("relation", relation.getRelation());
                map.put("relationId", relation.getId());
                Integer isDefault = relation.getIsDefault();
                map.put("isDefault", relation.getIsDefault());
                map.put("dutyList", customerMapper.selectCustomerIndexRelationPeople(customer.getId()));
                list.add(map);
            }
        }
        return BaseResult.ok(list);
    }

    public Customer selectDefaultRelationCustomer(Integer customerId) {
        RelationExample example = new RelationExample();
        example.createCriteria().andCustomerIdEqualTo(customerId).andIsDefaultEqualTo(YesOrNo.YES);
        List<Relation> relations = relationMapper.selectByExample(example);
        if (relations.size() > 0) {
            Customer customer = customerMapper.selectByPrimaryKey(relations.get(0).getRelateId());
            return customer;
        } else {
            return null;
        }
    }

    public BaseResult unbind(Relation relation) {
        RelationExample example = new RelationExample();
        example.createCriteria().andCustomerIdEqualTo(relation.getCustomerId()).andRelateIdEqualTo(relation.getRelateId());
        relationMapper.deleteByExample(example);
        return BaseResult.ok();
    }

    @Transactional
    public BaseResult setDefaultRelation(Relation relation) {

        RelationExample example = new RelationExample();
        example.createCriteria().andCustomerIdEqualTo(relation.getCustomerId()).andIsDefaultEqualTo(YesOrNo.YES);

        Relation relation1 = new Relation();
        relation1.setIsDefault(0);
        relationMapper.updateByExampleSelective(relation1, example);

        relation.setIsDefault(YesOrNo.YES);
        example.clear();
        example.createCriteria().andCustomerIdEqualTo(relation.getCustomerId()).andRelateIdEqualTo(relation.getRelateId());
        relationMapper.updateByExampleSelective(relation, example);
        return BaseResult.ok();
    }

    //查询可以看id的customer
    public List<Customer> selectMyRelationCustomer(Integer id) {
        RelationExample example = new RelationExample();
        example.createCriteria().andRelateIdEqualTo(id);
        List<Relation> relations = relationMapper.selectByExample(example);
        List<Customer> customerList = relations.stream().map(relation -> {
            Customer customer = customerMapper.selectByPrimaryKey(relation.getCustomerId());
            return customer;
        }).filter(customer -> customer != null).collect(Collectors.toList());
        return customerList;
    }

    public void insert(Relation relation) {
        relationMapper.insertSelective(relation);
    }

    public void insertDefault(Integer relateId, Integer customerId) {
        Relation relation = new Relation();
        relation.setRelateId(relateId);
        relation.setCustomerId(customerId);
        relation.setIsDefault(YesOrNo.YES);
        insert(relation);
    }

    public Customer selectPhoneNotNullFirst(Integer id) {
        List<Customer> customers = selectMyRelationCustomer(id);
        List<Customer> customerList = customers.stream().filter(customer -> StringUtils.isNotBlank(customer.getPhone())).collect(Collectors.toList());
        return customerList.size() > 0 ? customers.get(0) : null;
    }

    public List<Customer> selectMyManagerCustomer(Integer customerId) {
        List<Customer> list = new ArrayList();
        RelationExample example = new RelationExample();
        example.createCriteria().andRelateIdEqualTo(customerId);
        List<Relation> relations = relationMapper.selectByExample(example);
        for (Relation relation : relations) {
            Customer customer = customerMapper.selectByPrimaryKey(relation.getCustomerId());
            //Map map = JsonUtils.jsonToPojo(JsonUtils.objectToJson(customer), Map.class);
            //map.put("isDefault", relation.getIsDefault());
            if (customer != null) {
                list.add(customer);
            }
        }
        return list;
    }

    public void deleteByCutomerIds(Integer[] ids) {
        relationMapper.deleteByCustomerIds(ids);
    }

    public BaseResult update(Integer id, String relation) {
        return BaseResult.ok(relationMapper.updateRelation(id, relation));
    }

    public List<Relation> selectOnlyManagerCustomer(Integer userId) {
        RelationExample example = new RelationExample();
        example.createCriteria().andRelateIdEqualTo(userId);
        List<Relation> relations = relationMapper.selectByExample(example);
        return relations;
    }
}
